// 引入socketio客户端
import io from "../../node_modules/socket.io/client-dist/socket.io"
import { $baseURL } from "../js/common"
import { $id, $ } from "../js/tool"
import dayjs from "dayjs"

export default class Listener {
  constructor() {
    this.socket = io($baseURL, {
      transports: ["websocket"],
    })
    this.ip = null
    this.init()
  }

  init() {
    // 监听连接
    this.socket.on("connect", function () {
      console.log("%c" + "Connect Success", "color: #0f0")
    })

    this.socket.on("address", ip => {
      console.log(ip)
      this.ip = ip
    })

    this.addEventListener()

    // 监听：获取最新消息
    this.socket.on("add:message", data => {
      // 渲染最新的消息
      this.renderLatestMsg(data)
    })

    // 监听：系统消息
    this.socket.on("system:notice", data => {
      this.renderSystemNotice(data)
    })

    // 监听：当前在线人数
    this.socket.on("system:users", data => {
      this.updateCurrentOnlineUsers(data)
    })
  }

  // 添加监听
  addEventListener() {
    const _this = this

    $id("message").addEventListener("keydown", function (e) {
      if (e.key === "Enter" && e.target.value) {
        _this.sendMsg(e.target.value)
      }
    })

    $id("send").onclick = function () {
      let msg = $id("message").value
      msg && _this.sendMsg(msg)
    }
  }

  // 向服务器发送最新的消息
  sendMsg(data, title = "chat", ip = this.ip) {
    let time = dayjs().format("YYYY-MM-DD HH:mm:ss")
    this.socket.emit(title, { data, ip, time })
  }

  // 渲染消息列表
  renderLatestMsg(data) {
    let li = `<li class="${data.ip === this.ip ? "me" : ""}">
      <div class="avatar"></div>
      <div class="nt">
        <div class="name">${data.ip}</div>
        <div class="text">${data.data}</div>
      </div>
    </li>`
    $id("msg-list").insertAdjacentHTML("beforeend", li)
    let scrollHeight = $id("msg-list").scrollHeight
    $id("msg-list").scrollTo(0, scrollHeight)
  }

  // 渲染系统消息
  renderSystemNotice(data) {
    let div = `<div class="system-notice">
      <span>${data}</span>
    </div>`
    $id("msg-list").insertAdjacentHTML("beforeend", div)
    let scrollHeight = $id("msg-list").scrollHeight
    $id("msg-list").scrollTo(0, scrollHeight)
  }

  // 更新当前在线人数
  updateCurrentOnlineUsers(data) {
    $(".header span").innerHTML = data
  }
}
